<template>
	<div class="e-container">
		<el-card class="e-option-card-container">
			<template #header>
				<div class="e-card-header">
					<el-page-header title="返回" content="邮箱验证 (通过邮箱验证码找回密码)" @back="goBack" />
				</div>
			</template>
			<div class="e-optino-card-content">
				<el-steps :active="nowActive" align-center finish-status="success">
					<el-step title="填写用户名"></el-step>
					<el-step title="验证身份"></el-step>
					<el-step title="重置密码"></el-step>
					<el-step title="修改成功"></el-step>
				</el-steps>

				<div>
					<div class="stepForm" v-if="nowActive === 0">
						<el-form class="form-main" label-width="100px" label-position="top" @submit.prevent
							:model="userInfo" :rules="rules">
							<el-form-item label="用户名" prop="userId">
								<el-input @keyup.enter.native="submitUserId(userInfo.userId)" class="form-main-input" v-model="userInfo.userId" placeholder="请输入您的用户名">
								</el-input>
							</el-form-item>

							<el-form-item style="text-align: left;">
								<el-button style="width: 12.5rem;" type="primary" :loading="nextLoading"
									@click.native="submitUserId(userInfo.userId)">下一步
								</el-button>
							</el-form-item>
						</el-form>
					</div>
					<div class="stepForm" v-if="nowActive === 1">
						<el-form class="form-main" label-width="100px" label-position="top" @submit.prevent
							:model="userInfo" :rules="rules">
							<el-form-item label="用户名:"
								style="display: flex;text-align: left; margin: 0 auto;align-items: baseline;">
								<span style="margin: -15px 0 0 1rem;font-size: 18px;color: gray;">
									{{userInfo.userId}}
								</span>
							</el-form-item>
							<el-form-item label="邮箱验证码" prop="userId">
								<div style="width: 300px;text-align: left;">
									<el-input class="form-main-input" v-model="userInfo.emailCode" placeholder="验证码">
									</el-input>
									<el-button :disabled="disable" @click.native="sendEmail()">{{sendEmailTip}}
									</el-button>
								</div>
							</el-form-item>

							<el-form-item style="text-align: left;">
								<el-button style="width: 12.5rem;" type="primary" :loading="nextLoading"
									@click.native="checkEmailCode()">下一步
								</el-button>
							</el-form-item>
						</el-form>
					</div>

					<div class="stepForm" v-if="nowActive === 2">
						<el-form class="form-main" label-width="100px" label-position="top" @submit.prevent
							:model="userInfo" :rules="rules">
							<el-form-item label="新密码" prop="newPwd">
								<div style="display: flex;">
									<el-input class="form-main-input" v-model="userInfo.newPwd" placeholder="请输入新密码">
									</el-input>
								</div>
							</el-form-item>
							<el-form-item label="确认密码" prop="newPwd_confirm">
								<div style="display: flex;">
									<el-input class="form-main-input" v-model="userInfo.newPwd_confirm"
										placeholder="请确认新密码">
									</el-input>
								</div>
							</el-form-item>

							<el-form-item style="text-align: left;">
								<el-button style="width: 12.5rem;" type="primary" :loading="nextLoading"
									@click.native="updatePassword()">下一步
								</el-button>
							</el-form-item>
						</el-form>
					</div>

					<div style="height: auto;" v-if="nowActive === 3">
						<el-result icon="success" title="密码修改成功" sub-title="点击按钮返回登录页">
							<template #extra>
								<el-button type="primary" size="medium" @click.native="goLogin()">返回</el-button>
							</template>
						</el-result>
					</div>
				</div>

			</div>
		</el-card>
	</div>
</template>

<script>
	import Qs from 'qs';
	import {
		sha256
	} from 'js-sha256';
	export default {
		data() {
			const checkPassWord = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入您的密码'))
				} else if (value !== this.userInfo.newPwd) {
					callback(new Error("两次输入密码不一致"))
				} else {
					callback()
				}
			}
			return {
				nextLoading: false,
				disable: true,
				countdown: 60,
				nowActive: 0,
				sendEmailTip: '',
				checkToken: '',
				userInfo: {
					userId: '',
					emailCode: '',
					newPwd: '',
					newPwd_confirm: '',
					email: '',
				},
				rules: {
					userId: [{
						required: true,
						message: '请输入用户名',
						trigger: 'blur',
					}, ],
					newPwd: [{
						required: true,
						message: '请输入新密码',
						trigger: 'blur',
					}, ],
					newPwd_confirm: [{
						validator: checkPassWord,
						trigger: 'blur'
					}],
					description: [{
							required: true,
							message: '请输入资源描述',
							trigger: 'blur',
						},
						{
							max: 80,
							message: '字数不能超过80个',
							trigger: 'blur',
						},
					],
					hobby: [{
						required: true,
						message: '请选择资源分类标签',
						trigger: 'blur',
					}, ],
				}
			}
		},
		methods: {
			timing() {
				let that = this;
				let codeEmail = that.handleEmail(that.userInfo.email);
				setInterval(() => {
					if (that.countdown > 0) {
						that.countdown -= 1;
						that.sendEmailTip = '已发送验证码至' + codeEmail + '(' + that.countdown + 's)';
					} else {
						that.sendEmailTip = '重新发送';
						that.disable = false;
						return;
					}
				}, 1000); //反复执行函数本身
			},
			goBack() {
				this.$router.push('/forget');
			},
			goLogin(){
				this.$router.push('/login');
			},
			handleEmail(email) {
				let new_email = email;
				if (String(email).indexOf('@') > 0) {
					let str = email.split('@');
					let _s = '';
					//console.log(str[0].length);
					let formerLen = Math.floor(str[0].length / 3);
					// console.log(formerLen);

					let latterLen = Math.floor(str[0].length / 3) - 1
					// console.log(latterLen)
					if (str[0].length > 3) { //@前面多于3位
						for (let i = 0; i < str[0].length - formerLen - latterLen; i++) {
							_s += '*';
						}
						_s += str[0].substr(str[0].length - latterLen, str[0].length);
						new_email = str[0].substr(0, formerLen) + _s + '@' + str[1];
					} else { //@前面小于等于于3位
						for (let i = 1; i < str[0].length; i++) {
							_s += '*'
						}
						new_email = str[0].substr(0, 1) + _s + '@' + str[1]
					}
				}
				return new_email;
			},
			next() {
				this.nextLoading = true;
			},
			nextOver(isNext) {
				if (isNext) {
					setTimeout(() => {
						if (this.nowActive++ > 3) this.nowActive = 0;
					}, 100)
				}
				this.nextLoading = false;
			},
			submitUserId(ruserId) {
				let that = this;
				let isNext = false;
				that.next();
				// console.log(this.nowActive)				
				// return;

				this.$axios({
					url: 'http://localhost:8081/getEmail',
					method: 'post',
					headers: {},
					transformRequest: [function(data) {
						// 对 data 进行任意转换处理
						return Qs.stringify(data);
					}],
					data: {
						userId: ruserId,
					},
					transformResponse: [function(data) {
						// 对接收的 data 进行任意转换处理
						let result = JSON.parse(data);
						// console.log(result.code)
						if (result.code === 200) {
							isNext = true;
							that.userInfo.email = result.email;
							that.$message.success("已发送邮箱验证码到您的邮箱");
						} else {
							that.$message.error(result.msg);
						}
						return data;
					}],
				}).catch(function(error) {
					// console.log(error);
					if (error.response) {
						// 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
						that.$message.error("服务器响应出错，请稍后再试");
						// console.log(error.response.data);
						// console.log(error.response.status);
						// console.log(error.response.headers);
					} else if (error.request) {
						// 请求已经成功发起，但没有收到响应
						// `error.request` 在浏览器中是 XMLHttpRequest 的实例，
						// 而在node.js中是 http.ClientRequest 的实例
						that.$message.error("请求服务器错误或超时,请稍后再试");
					} else {
						// 发送请求时出了点问题
						that.$message.error("发送请求出现问题，请稍后再试");
					}
				}).then(() => {
					that.timing();
					setTimeout(() => {
						that.nextOver(isNext);
					}, 200);
					that.sendEmail();
				});
			},
			sendEmail() {
				let that = this;
				let isNext = false;
				this.$axios({
					url: 'http://localhost:8081/findPasswordSendEmail',
					method: 'post',
					transformRequest: [function(data) {
						// 对 data 进行任意转换处理
						return Qs.stringify(data);
					}],
					data: {
						userId: that.userInfo.userId,
						email: that.userInfo.email
					},
					transformResponse: [function(data) {
						// 对接收的 data 进行任意转换处理
						let result = JSON.parse(data);
						// console.log(result.code)
						if (result.code === 200) {
							isNext = true;
						} else {
							isNext = false;
							that.$message.error(result.msg);
						}
						return data;
					}],
				}).catch(function(error) {
					// console.log(error);
					if (error.response) {
						// 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
						that.$message.error("服务器响应出错，请稍后再试");
						// console.log(error.response.data);
						// console.log(error.response.status);
						// console.log(error.response.headers);
					} else if (error.request) {
						// 请求已经成功发起，但没有收到响应
						// `error.request` 在浏览器中是 XMLHttpRequest 的实例，
						// 而在node.js中是 http.ClientRequest 的实例
						that.$message.error("请求服务器错误或超时,请稍后再试");
					} else {
						// 发送请求时出了点问题
						that.$message.error("发送请求出现问题，请稍后再试");
					}
				});
			},
			checkEmailCode() {
				let that = this;
				let isNext = false;
				this.$axios({
					url: 'http://localhost:8081/checkVerificationCode',
					method: 'post',
					transformRequest: [function(data) {
						// 对 data 进行任意转换处理
						return Qs.stringify(data);
					}],
					data: {
						userId: that.userInfo.userId,
						verificationCode: that.userInfo.emailCode
					},
					transformResponse: [function(data) {
						// 对接收的 data 进行任意转换处理
						let result = JSON.parse(data);
						// console.log(result.code)
						if (result.code === 200) {
							isNext = true;
							that.checkToken = result.checkToken;
							that.$message.success(result.msg);
						} else {
							isNext = false;
							that.$message.error(result.msg);
						}
						return data;
					}],
				}).catch(function(error) {
					// console.log(error);
					if (error.response) {
						// 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
						that.$message.error("服务器响应出错，请稍后再试");
						// console.log(error.response.data);
						// console.log(error.response.status);
						// console.log(error.response.headers);
					} else if (error.request) {
						// 请求已经成功发起，但没有收到响应
						// `error.request` 在浏览器中是 XMLHttpRequest 的实例，
						// 而在node.js中是 http.ClientRequest 的实例
						that.$message.error("请求服务器错误或超时,请稍后再试");
					} else {
						// 发送请求时出了点问题
						that.$message.error("发送请求出现问题，请稍后再试");
					}
				}).then(() => {
					that.timing();
					setTimeout(() => {
						that.nextOver(isNext);
					}, 200);
				});
			},
			updatePassword() {
				let that = this;
				let isNext = false;
				this.$axios({
					url: 'http://localhost:8081/findPassword',
					method: 'post',
					transformRequest: [function(data) {
						// 对 data 进行任意转换处理
						return Qs.stringify(data);
					}],
					data: {
						checkToken: that.checkToken,
						newPassword: sha256(that.userInfo.newPwd_confirm),
						userId: that.userInfo.userId
					},
					transformResponse: [function(data) {
						// 对接收的 data 进行任意转换处理
						let result = JSON.parse(data);
						// console.log(result.code)
						if (result.code === 200) {
							isNext = true;
							that.$message.success(result.msg);
						} else {
							isNext = false;
							that.$message.error(result.msg);
						}
						return data;
					}],
				}).catch(function(error) {
					// console.log(error);
					if (error.response) {
						// 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
						that.$message.error("服务器响应出错，请稍后再试");
						// console.log(error.response.data);
						// console.log(error.response.status);
						// console.log(error.response.headers);
					} else if (error.request) {
						// 请求已经成功发起，但没有收到响应
						// `error.request` 在浏览器中是 XMLHttpRequest 的实例，
						// 而在node.js中是 http.ClientRequest 的实例
						that.$message.error("请求服务器错误或超时,请稍后再试");
					} else {
						// 发送请求时出了点问题
						that.$message.error("发送请求出现问题，请稍后再试");
					}
				}).then(() => {
					that.timing();
					setTimeout(() => {
						that.nextOver(isNext);
					}, 200);
				});
			}
		}
	}
</script>

<style>
	a {
		color: #000000;
		text-decoration: none;
	}

	* {
		margin: 0;
		padding: 0;
	}

	.form-main-input {
		width: 300px;
		margin: 0 10px 10px 0;
	}

	.stepForm {
		display: flex;
		/* flex-direction: column; */
		margin: 25px 0;
		justify-content: center;
	}

	.e-container {
		position: absolute;
		height: auto;
		width: 100%;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.e-option-card-container {
		/* display: flex;
		background-color: #FFFFFF;*/
		height: 70%;
		width: 80%;
		margin-top: 4rem;
		/* border: 1px solid #d9d9d9; */
		/* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12), 0 0 10px rgba(0, 0, 0, 0.04); */
	}

	.e-optino-card-content {
		display: block;
	}

	.e-optino-card-detail {
		text-align: left;
		margin: 3rem 2rem 0 2rem;
		color: #767676;
	}

	.e-optino-card-image {
		margin-top: 1rem;
	}

	.e-optino-card-title {
		font-size: 1.125rem;
		font-weight: 600;
		margin-top: 1rem;
		transition: .2s;
	}

	.e-optino-card-title-no {
		font-size: 1.125rem;
		font-weight: 600;
		margin-top: 1rem;
		color: #838383;
		transition: .2s;
	}

	.e-optino-card {
		width: 350px;
		margin: 0 1.5625rem 1.25rem 1.25rem;
		background-color: #f7f7f7;
		height: 25rem;
		transition: background-color .5s;
	}

	.e-optino-card:hover {
		background-color: #dedede;
		transition: background-color .5s;
	}

	.e-optino-card:hover .e-optino-card-title {
		font-size: 1.375rem;
		transition: .2s;
	}

	.e-optino-card:hover .e-optino-card-title-no {
		font-size: 1.375rem;
		transition: .2s;
	}
</style>
